<?php
declare (strict_types=1);

namespace app\service\logic\common\user;

use app\model\communal\ExpertAmountModel;
use app\model\communal\ExpertStatisticsModel;
use app\service\logic\BaseService;
use think\facade\Db;

final class ExpertAmountService extends BaseService
{
    protected string $modelClassName = 'ExpertAmountModel';

    /**
     * 结算操作
     *
     * @param $params
     * @return mixed
     */
    public function back($params)
    {
        // 获取当前专家金额总量
        $staModel = ExpertStatisticsModel::where('expert_id', $params['expert_id'])->findOrEmpty();
        Db::connect('communal')->transaction(function () use ($params, $staModel, &$model) {
            if ($staModel->isEmpty()) {
                $amountCount = $amountAvailableCount = $params['amount_count'];
            } else {
                $amountCount = bcadd((string)$params['amount_count'], (string)$staModel['amount_count'], 2);
                $amountAvailableCount = bcadd((string)$params['amount_count'], (string)$staModel['amount_available_count'], 2);
            }
            $staModel->save(['expert_id' => $params['expert_id'], 'amount_count' => $amountCount, 'amount_available_count' => $amountAvailableCount]);
            $params['amount_balance'] = $amountCount;
            $model = ExpertAmountModel::create($params);
        });
        return $model;
    }

    /**
     * @param $type
     * @return string
     */
    public function getTypeMap($type)
    {
        $map = [1 => '企业订单结算', 2 => '个人订单结算', 3 => '提现'];
        return $map[$type];
    }
}
